<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="title" :visible.sync="dialogOpen">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      ref="addFormRef"
      label-width="120px"
      :model="formData"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeeSimple"
        >
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button
          type="primary"
          size="small"
          @click="clickHandle"
        >确定</el-button>
        <el-button
          size="small"
          @click="$emit('update:showDialog', false)"
        >取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartDetail,
  editDepartments
} from '@/api/departments.js'
import { getEmployeeSimple } from '@/api/employees.js'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    treeNode: {
      type: Object,
      required: true
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const checkName = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let isReapt = false
      if (this.isEdit) {
        isReapt = depts
          .filter(
            (item) =>
              item.id !== this.formData.id && item.pid === this.treeNode.pid
          )
          .some((item) => item.name === value)
      } else {
        // 在新增中判断不能与上级同名
        if (value === this.treeNode.name) {
          return callback(new Error('不能和上级部门同名'))
        }
        // 过滤list得到当前treeNode的children
        isReapt = depts
          .filter((item) => item.pid === this.treeNode.id)
          .some((item) => item.name === value)
      }
      isReapt ? callback(new Error('输入的名称与子节点重复了')) : callback()
    }
    // 检查编码重复
    const checkCodeRepeat = async(rule, value, callback) => {
      // 先要获取最新的组织架构数据
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.isEdit) {
        isRepeat = depts.some(
          (item) => item.id !== this.formData.id && item.code === value && value
        )
      } else {
        isRepeat = depts.some((item) => item.code === value && value) // 这里加一个 value不为空 因为我们的部门有可能没有code
      }
      isRepeat
        ? callback(new Error(`组织架构中已经有部门使用${value}编码`))
        : callback()
    }

    return {
      dialogOpen: false,
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      // 定义校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 300,
            message: '部门介绍要求1-50个字符'
          }
        ]
      },
      peoples: []
    }
  },
  computed: {
    title() {
      return this.isEdit ? '编辑部门' : '添加部门'
    }
  },
  watch: {
    dialogOpen(val) {
      this.$emit('update:showDialog', val)
    },
    showDialog: {
      handler: function(val) {
        this.dialogOpen = val
      },
      immediate: true
    }
  },
  created() {
    // console.log('created')
    if (this.isEdit) {
      this.getDepartDetail()
    }
  },
  methods: {
    async getEmployeeSimple() {
      try {
        const data = await getEmployeeSimple()
        // console.log(data)
        this.peoples = data
      } catch (error) {
        console.log(error)
      }
    },
    // 确定按钮
    clickHandle() {
      // 获取表单el-form组件实例 调用组件的validate方法
      this.$refs.addFormRef.validate(async(isOk) => {
        console.log(isOk)
        if (isOk) {
          if (this.isEdit) {
            await editDepartments(this.formData)
          } else {
            await addDepartments({
              ...this.formData,
              pid: this.treeNode.id
            })
          }

          // 成功后的处理 ： 重置表单,重置表单不能简单的直接赋值
          // 重置可以直接调用el-form组件的重置方法即可
          this.$refs.addFormRef.resetFields()
          // 通知父组件更新列表数据
          this.$emit('addDept')
          // 关闭弹窗
          this.dialogOpen = false
        }
      })
    },
    async getDepartDetail() {
      try {
        // this.treeNode 是来自于props，它是异步的 所以这里会出现id为undefined是因为数据还没传过来
        this.formData = await getDepartDetail(this.treeNode.id)
        console.log(this.treeNode)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>
</style>
